#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Video Platform Python Service
视频平台Python爬虫服务

提供视频解析、数据抓取等核心功能的API服务
"""

import sys
import os
import logging
from contextlib import asynccontextmanager

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

from api.endpoints import video
from api.models.video_models import ErrorResponse

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('logs/python-service.log')
    ]
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("🚀 Python爬虫服务启动中...")
    
    # 创建日志目录
    os.makedirs("logs", exist_ok=True)
    
    logger.info("✅ Python爬虫服务启动完成")
    
    yield
    
    # 关闭时执行
    logger.info("🛑 Python爬虫服务正在关闭...")


# 创建FastAPI应用
app = FastAPI(
    title="Video Platform Crawler Service",
    description="视频平台爬虫服务 - 提供视频解析、数据抓取等核心功能",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:3000",  # Vue开发服务器
        "http://localhost:8080",  # Java配置服务
        "http://127.0.0.1:3000",
        "http://127.0.0.1:8080"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 全局异常处理
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    """HTTP异常处理"""
    return JSONResponse(
        status_code=exc.status_code,
        content=ErrorResponse(
            code=exc.status_code,
            message=str(exc.detail),
            detail=f"请求路径: {request.url.path}"
        ).dict()
    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """请求验证异常处理"""
    return JSONResponse(
        status_code=422,
        content=ErrorResponse(
            code=422,
            message="请求参数验证失败",
            detail=str(exc)
        ).dict()
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content=ErrorResponse(
            code=500,
            message="服务器内部错误",
            detail="请联系管理员或查看日志"
        ).dict()
    )


# 注册路由
app.include_router(video.router)


# 根路径
@app.get("/", tags=["root"])
async def root():
    """服务根路径"""
    return {
        "service": "Video Platform Crawler Service",
        "version": "1.0.0",
        "status": "running",
        "docs": "/docs",
        "health": "/api/v1/health"
    }


# 健康检查端点（备用）
@app.get("/ping", tags=["health"])
async def ping():
    """简单的健康检查"""
    return {"status": "pong"}


if __name__ == "__main__":
    import uvicorn
    
    # 开发环境配置
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,  # 开发模式下启用热重载
        log_level="info",
        access_log=True
    )